using AutoMapper;
using MediatR;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure;
using S.M.SmartMedical.Infrastructure.BaseRepository;

namespace S.M.SmartMedical.API.Write.Application.Handler
{
    /// <summary>
    /// 删除轮播图命令处理器
    /// </summary>
    public class DeleteCarouselHandler : IRequestHandler<DeleteCarouselCommand, APIResult<bool>>
    {
        private readonly IRepository<Carousel> _carouselRepository;
        private readonly ILogger<DeleteCarouselHandler> _logger;
        private readonly MyDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="carouselRepository">轮播图仓储</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="context">数据库上下文</param>
        public DeleteCarouselHandler(
            IRepository<Carousel> carouselRepository,
            ILogger<DeleteCarouselHandler> logger,
            MyDbContext context)
        {
            _carouselRepository = carouselRepository;
            _logger = logger;
            _context = context;
        }

        /// <summary>
        /// 处理删除轮播图命令
        /// </summary>
        /// <param name="request">删除轮播图命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public async Task<APIResult<bool>> Handle(DeleteCarouselCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理删除轮播图，ID：{Id}，类型：{Type}", request.Id, request.Id.GetType());

                // 检查ID是否有效
                if (request.Id <= 0)
                {
                    _logger.LogWarning("无效的轮播图ID：{Id}", request.Id);
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "无效的轮播图ID",
                        Data = false
                    };
                }

                // 检查轮播图是否存在
                var existingCarousel = await _carouselRepository.GetByIdAsync(request.Id);
                if (existingCarousel == null)
                {
                    _logger.LogWarning("轮播图不存在，ID：{Id}", request.Id);
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "轮播图不存在",
                        Data = false
                    };
                }

                // 检查是否已删除
                if (existingCarousel.IsDeleted)
                {
                    _logger.LogWarning("轮播图已删除，ID：{Id}", request.Id);
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "轮播图已删除",
                        Data = false
                    };
                }

                // 软删除轮播图
                existingCarousel.IsDeleted = true;
                existingCarousel.UpdateTime = DateTime.Now;
                existingCarousel.UpdateUserName = "admin"; // 实际应用中应该从登录用户获取

                // 更新到仓储
                var result = await _carouselRepository.UpdateAsync(existingCarousel);

                // 保存到数据库
                var saveResult = await _context.SaveChangesAsync(cancellationToken);

                if (saveResult > 0)
                {
                    _logger.LogInformation("轮播图删除成功，ID：{Id}", existingCarousel.Id);
                    return new APIResult<bool>
                    {
                        Code = APIEnum.OK,
                        Message = "轮播图删除成功",
                        Data = true
                    };
                }
                else
                {
                    _logger.LogError("轮播图删除失败，数据库保存失败，ID：{Id}", request.Id);
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "轮播图删除失败，请稍后重试",
                        Data = false
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除轮播图过程中发生异常，ID：{Id}", request.Id);
                return new APIResult<bool>
                {
                    Code = APIEnum.Fail,
                    Message = "删除轮播图失败，系统异常",
                    Data = false
                };
            }
        }
    }
}